<template>
  <div class="content" v-loading="submitBtn">
    <div class="scroll-view-box">
      <el-form label-width="120px" :inline="true" :model="formData" :rules="formRules" ref="elFrom"
        label-position="top">
        <el-form-item label="归属工程经理" prop="engineering_manager_id">
          <el-select filterable v-model="formData.engineering_manager_id" placeholder="请选择归属工程经理" clearable class="input-width">
            <el-option v-for="(item, idx) in gcList" :label="item.name" :value="item.id" :key="idx"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工长名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入工长名称" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话" v-input-limit="0" clearable
            class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="性别" required>
          <el-radio-group v-model="formData.sex" class="input-width">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="formData.age" placeholder="请输入年龄" v-input-limit="0" clearable class="input-width">
            <span slot="suffix">岁</span>
          </el-input>
        </el-form-item>
        <el-form-item label="工种" prop="job_type">
          <el-input v-model="formData.job_type" placeholder="请输入工种" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="省市区" prop="city">
          <el-cascader v-model="formData.city" :options="cityList" placeholder="请选择省市区" clearable class="input-width"
            :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入详细地址" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="id_card_number">
          <el-input v-model="formData.id_card_number" placeholder="请输入身份证号码" clearable class="input-width"></el-input>
        </el-form-item>
        <el-form-item label="身份证文件" prop="id_card_file">
          <div class="id-card-box input-width">
            <el-upload class="avatar-uploader" ref="file1" action="#" :show-file-list="false" :multiple="false"
              accept="image/*" :limit="1" list-type="picture-card" :auto-upload="false"
              :on-change="(file) => { changeFile(file, 'tx') }">
              <div v-if="!formData.id_card_file1">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <div class="id-card-tips">请上传人像面</div>
              </div>
              <div v-else class="upload-box">
                <img :src="formData.id_card_file1.url">
                <i class="el-icon-delete" @click.stop="delFileFunc('tx')"></i>
              </div>
            </el-upload>
            <el-upload class="avatar-uploader" ref="file2" action="#" :show-file-list="false" :multiple="false"
              accept="image/*" :limit="1" list-type="picture-card" :auto-upload="false"
              :on-change="(file) => { changeFile(file, 'gh') }">
              <div v-if="!formData.id_card_file2">
                <i class="el-icon-plus avatar-uploader-icon"></i>
                <div class="id-card-tips">请上传国徽面</div>
              </div>
              <div v-else class="upload-box">
                <img :src="formData.id_card_file2.url">
                <i class="el-icon-delete" @click.stop="delFileFunc('gh')"></i>
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import foremanApi from '@/api/foremanApi'
import adminApi from '@/api/adminApi'
import commonApi from "@/api/common";

export default {
  name: 'foremanAdd',
  data() {
    const fileRule = (rule, value, callback) => {
      if (!this.formData.id_card_file1) {
        callback(new Error('请上传身份证文件'))
      } else if (!this.formData.id_card_file2) {
        callback(new Error('请上传身份证文件'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      gcList: [],
      cityList: [],
      editType: 'add',
      formData: {
        id: '',
        name: '',
        phone: '',
        engineering_manager_id: '',
        sex: 1,
        age: '',
        job_type: '',
        city: [],
        address: '',
        id_card_number: '',
        id_card_file1: null,
        id_card_file2: null,
        del_file: [],
      },
      formRules: {
        name: { required: true, message: "请输入工长名称", trigger: "change", },
        phone: { required: true, message: "请输入电话", trigger: "change", },
        age: { required: true, message: "请输入年龄", trigger: "change", },
        engineering_manager_id: { required: true, message: "请选择工程经理", trigger: "change", },
        job_type: { required: true, message: "请输入工种", trigger: "change", },
        city: { required: true, message: "请选择省市区", trigger: "change", },
        address: { required: true, message: "请输入详细地址", trigger: "change", },
        id_card_number: { required: true, message: "请输入身份证号码", trigger: "change", },
        id_card_file: [{ required: true, validator: fileRule, trigger: 'change' }],
      },
      submitBtn: false,
    };
  },
  computed: {
  },
  mounted() {
    let id = this.$route.query.sn
    if (id) {
      foremanApi.getForemanDetails({ foreman_id: id }).then(res => {
        console.log(res, '工长详情')
        if (res.code == 200) {
          let formData = this.formData
          let data = res.data
          data.foreman_list[0].url = data.foreman_list[0].file_url
          data.foreman_list[1].url = data.foreman_list[1].file_url
          formData.id = id
          formData.name = data.name
          formData.phone = data.phone
          formData.sex = data.sex
          formData.age = data.age
          formData.job_type = data.job_type
          formData.city = [data.province_id, data.city_id, data.county_id]
          formData.address = data.address
          formData.id_card_number = data.id_card_number
          formData.engineering_manager_id = data.engineering_manager_id
          formData.id_card_file1 = data.foreman_list[0]
          formData.id_card_file2 = data.foreman_list[1]
          this.editType = 'update'
        }

        this.loading = false
      })
    }
    this.getList()
  },
  methods: {
    // 选择文件
    changeFile(file, type) {
      if (type == 'tx') {
        this.formData.id_card_file1 = file
      } else {
        this.formData.id_card_file2 = file
      }
    },
    delFileFunc(type) {
      if (type == 'tx') {
        if (this.formData.id_card_file1.file_id) {
          this.formData.del_file.push(this.formData.id_card_file1.file_id);
        }

        this.$refs.file1.clearFiles();
        this.formData.id_card_file1 = null
      } else {
        if (this.formData.id_card_file2.file_id) {
          this.formData.del_file.push(this.formData.id_card_file2.file_id);
        }

        this.$refs.file2.clearFiles();
        this.formData.id_card_file2 = null
      }
    },
    // 提交
    saveSubmit() {
      this.$refs['elFrom'].validate((valid) => {
        if (valid) {
          let formInline = this.formData
          let data = {
            name: formInline.name,
            phone: formInline.phone,
            engineering_manager_id: formInline.engineering_manager_id,
            sex: formInline.sex,
            age: formInline.age,
            job_type: formInline.job_type,
            name: formInline.name,
            province_id: formInline.city[0],
            city_id: formInline.city[1],
            county_id: formInline.city[2],
            address: formInline.address,
            id_card_number: formInline.id_card_number,
            del_file: formInline.del_file,
          };
          let formdata = new FormData();
          if (this.editType == 'add') {
            formdata.append("id_card_file[]", formInline.id_card_file1.raw);
            formdata.append("id_card_file[]", formInline.id_card_file2.raw);
          } else {
            data.foreman_id = formInline.id;
            if (!formInline.id_card_file1.file_id) {
              formdata.append("id_card_file[]", formInline.id_card_file1.raw);
            }
            if (!formInline.id_card_file2.file_id) {
              formdata.append("id_card_file[]", formInline.id_card_file2.raw);
            }
          }
          formdata.append("data", JSON.stringify(data));

          this.submitBtn = true;
          if (this.editType == 'add') {
            foremanApi.addForeman(formdata).then(res => {
              console.log(res, "添加")
              if (res.code == 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.warning(res.message);
              }
              this.submitBtn = false;
            })
          } else {
            foremanApi.updForeman(formdata).then(res => {
              console.log(res, "修改")
              if (res.code == 200) {
                this.$message({
                  message: "更新成功",
                  type: "success",
                });
                this.cancelFunc()
              } else {
                this.$message.warning(res.message);
              }
              this.submitBtn = false;
            })
          }
        } else {
          return false;
        }
      });
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
    /****************获取关联数据*********************/
    getList() {
      // 获取工程经理列表
      adminApi.getAdminList({
        page: 1,
        num: 999,
        position_id_arr: [7],
        identity: 2,
      }).then((res) => {
        console.log(res, "获取工程经理列表");
        if (res.code == 200) {
          this.gcList = res.data.list;
        }
      })
      // 获取省市区
      commonApi.getAreaList().then((res) => {
        console.log(res, "省市区");
        if (res.code == 200) {
          this.cityList = res.data;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/addPage.scss";

.id-card-box {
  width: 500px;
  display: flex;
}

.avatar-uploader+.avatar-uploader {
  margin-left: 20px;
}

.avatar-uploader {
  width: 50%;

  .id-card-tips {
    margin-top: 20px;
    font-size: 12px;
    color: #606266;
    height: 12px;
  }

  .upload-box {
    width: 100%;
    height: 100%;
    border-radius: 6px;
    position: relative;
    overflow: hidden;

    &:hover {
      .el-icon-delete {
        opacity: 1;
      }
    }

    .el-icon-delete {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, .5);
      color: #fff;
      opacity: 0;
      transition: opacity .3s;
      font-size: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }

  }

  img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
}

::v-deep .el-upload--picture-card {
  width: 100%;
  height: 100px;
  line-height: 0px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>